/*
 * PURION_Producer.java
 *
 * Created on 2008년 1월 6일 (일), 오전 7:17
 */

package PuriON;


import PuriON_Chat.*;
import java.awt.FileDialog;
import java.io.*;

import java.net.Socket;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.media.*;
import javax.swing.*;
import javax.swing.tree.*;

/**
 *
 * @author  hyukmini
 */
public class PURION_Producer extends javax.swing.JInternalFrame {
    
    PURION_Main parent = null;
    PURION_Transmit trans = null;
    
    /* 설정 부분 */
    String codec = null;
    Integer frame_rate = null;
    Float quality_rate = null;
    
   /* 컨트롤러와 연결될 상태 표시 모델입니다. */
    DefaultListModel model = null;
    DefaultTreeModel tree = null;
    DefaultMutableTreeNode root = null;
    private PURION_Chat_Repeater chater;
    private Thread thread_chat;
    
    /** Creates new form PURION_Producer */
    PURION_Producer(PURION_Main p, String t) {
        super(t);
        parent = p;

        this.initComponents();
        this.setLocation(30, 30);
        
        /* 설정 파일 읽어오기 */
        loadSettingFile("./setting");
        
        /* UI 처리 부분 */
        model = new DefaultListModel();
        tree = new DefaultTreeModel(null);
        root = new DefaultMutableTreeNode("ASDF");
        tree.setRoot(root);
        
        DefaultMutableTreeNode child = new DefaultMutableTreeNode("Node Label");
        
        child.setUserObject(new JProgressBar());
        root.add(child);
        //this.sourceList.setModel(model);
        //this.comboSource.setModel(model);
        //this.statusTree.setModel(tree);
        this.setVisible(true);
        
        //채팅모듈 생성
        chater = new PURION_Chat_Repeater(jTextArea1);    
        thread_chat = new Thread(chater);
        thread_chat.start();
        chater.sendAll("'"+t+"'" + "방이 개설 되었습니다.");
    }
    
    public void loadSettingFile(String fn) {
        int i = 0;
        InputStream in = null;
        try {
            in = new FileInputStream(new File(fn));
        } catch (FileNotFoundException e) {
            System.out.println(e);
            return;
        } catch (IOException e) {
            System.out.println(e);
        }
        try {
            String temp = "";
            while ((i = in.read()) != -1) {       
                temp = temp + new Character((char) i);
            }
            StringTokenizer token = new StringTokenizer(temp, "|");            
            
            token.nextToken();
            token.nextToken();
            
            codec = token.nextToken();
            frame_rate = new Integer(token.nextToken());
            quality_rate = new Float(token.nextToken());
            
            System.out.println(codec);
            System.out.println(frame_rate);
            System.out.println(quality_rate);
            
            in.close();
        } catch (IOException e1) {
            System.out.println(e1);
        }
        System.err.println("PURION_Setting : ./setting is loaded");
    }
    public void initTrans() {
        
        StringTokenizer token = new StringTokenizer((String)(comboSource.getSelectedItem()), "|");        
        String file = token.nextToken();
        String dir = token.nextToken();
        trans = new PURION_Transmit(this, new MediaLocator("file:/" + dir + file),
                codec, frame_rate, quality_rate);
        
        Thread t = new Thread(trans);
        t.start();
        
        PURION_Player video = new PURION_Player("file:/" + dir + file, true);
        Thread t1 = new Thread(video);
        t1.start();        
        parent.addComopnent(video);
        
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ie) {
            System.err.println(ie);
        }
    }
    public void addTransList(String ipaddr) {
        /* 상대방의 30000번 포트로 전송한다. */
        Thread t = new Thread(new PURION_MultiTransmit(trans.rtpMgrs, trans.dataOutput, ipaddr, 30000));
        t.start();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane2 = new javax.swing.JLayeredPane();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        butStartShare = new javax.swing.JButton();
        butStopShare = new javax.swing.JButton();
        comboSource = new javax.swing.JComboBox();
        jLayeredPane3 = new javax.swing.JLayeredPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jTextField1 = new javax.swing.JTextField();
        butMsgSend = new javax.swing.JButton();
        jLayeredPane1 = new javax.swing.JLayeredPane();
        jLabel4 = new javax.swing.JLabel();
        jLayeredPane4 = new javax.swing.JLayeredPane();
        jLabel2 = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/PuriON/reources/Plus.png"))); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jButton2.setBounds(0, 30, 40, 30);
        jLayeredPane2.add(jButton2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/PuriON/reources/Minus.png"))); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jButton3.setBounds(40, 30, 40, 30);
        jLayeredPane2.add(jButton3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        butStartShare.setIcon(new javax.swing.ImageIcon(getClass().getResource("/PuriON/reources/Play.png"))); // NOI18N
        butStartShare.setText("방송시작");
        butStartShare.setBorder(null);
        butStartShare.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butStartShareActionPerformed(evt);
            }
        });
        butStartShare.setBounds(110, 30, 110, 30);
        jLayeredPane2.add(butStartShare, javax.swing.JLayeredPane.DEFAULT_LAYER);

        butStopShare.setIcon(new javax.swing.ImageIcon(getClass().getResource("/PuriON/reources/Pause.png"))); // NOI18N
        butStopShare.setText("방송중지");
        butStopShare.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butStopShareActionPerformed(evt);
            }
        });
        butStopShare.setBounds(230, 30, 110, 30);
        jLayeredPane2.add(butStopShare, javax.swing.JLayeredPane.DEFAULT_LAYER);

        comboSource.setBounds(0, 0, 340, 21);
        jLayeredPane2.add(comboSource, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jScrollPane3.setViewportView(jTextArea1);

        jScrollPane3.setBounds(0, 0, 340, 160);
        jLayeredPane3.add(jScrollPane3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
        });
        jTextField1.setBounds(0, 170, 260, 20);
        jLayeredPane3.add(jTextField1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        butMsgSend.setText("보내기");
        butMsgSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butMsgSendActionPerformed(evt);
            }
        });
        butMsgSend.setBounds(270, 170, 69, 23);
        jLayeredPane3.add(butMsgSend, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLayeredPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/PuriON/reources/Chat.png"))); // NOI18N
        jLabel4.setText("  현재 방송에 참여중인 사용자와 대화");
        jLabel4.setBounds(10, 10, 300, 30);
        jLayeredPane1.add(jLabel4, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLayeredPane4.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/PuriON/reources/Anouncement.png"))); // NOI18N
        jLabel2.setText("  방송 데이터 추가 및 방송 관리");
        jLabel2.setBounds(10, 10, 304, 35);
        jLayeredPane4.add(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLayeredPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 347, Short.MAX_VALUE)
                    .addComponent(jLayeredPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 347, Short.MAX_VALUE)
                    .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 338, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLayeredPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLayeredPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLayeredPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLayeredPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    /* 리스트내 스트리밍 목록을 참여자에게 전송합니다. */
    private void butStartShareActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butStartShareActionPerformed
        // TODO add your handling code here:

        /*
         *     public void sendQuery() {
        
        String id = idField.getText();
        String query = "SELECT * FROM User where ID = '" + id + "'";
      
        loginquery = new PURION_SendQuery(this, query);
        Thread t = new Thread(loginquery);
        parent.setLoginID(id);
        this.switchEnable();
        t.start();
    }*/
        
        /* 데이터베이스로부터 보내줘야할 아이피 주소를 받아온다 */
        // 지금은 방을 개설하고, 선택 공유 하기전에 방송 볼 사람들이 들어온 후, 선택공유를 하면 들어온 사람에게만 보여준다.
        //중간에 들어온 사람은 볼 수 없다.
        //이를 위해 채팅서버소캣 부분에 trans.addTarget 함수를 넣는 방안을 생각중이나 여의치 않음.
        
        //ps. 파일 여러개 차례대로 전송을 테스트 해봄.
        //하나 재생중에 재생중단하고 다른파일 재생시켜봄. 결과 => 안됨. 이유모름.
        
        if(comboSource.getSelectedIndex() < 0 ) {
            JOptionPane.showMessageDialog(this, "방송을 시작할 데이터 원본을 선택하세요");
            return;
        }
        
        Vector temp = chater.getVector();
        //temp.add(this.textIPAddress1.getText());
        //temp.add("218.101.153.13");
        System.out.println(temp);
        this.initTrans();
        
        for(int i = 0; i < temp.size(); i++) {
            Socket soc = (Socket)temp.get(i);
            this.addTransList(soc.getInetAddress().getHostAddress());
        }
        
        //this.addTransList(temp);
        chater.sendAll("<" + (String) comboSource.getSelectedItem() + "> 방송이 시작 되었습니다.");

        /*
        try {

            Thread.sleep(10000);
        } catch (InterruptedException ex) {
            Logger.getLogger(PURION_Producer.class.getName()).log(Level.SEVERE, null, ex);
        }
       */
        //trans.addTarget("218.101.153.13", 30000); //박진원집 아이피였음 이것은 방송중에 시청자가 추가될 수 있는지 여부를 판단위해 테스트한것. 결과는 가능.
        //trans.addTarget 함수는 실행중에 호출해도 정상작동함.
}//GEN-LAST:event_butStartShareActionPerformed

    private void butStopShareActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butStopShareActionPerformed
        // TODO add your handling code here:
        
        trans.stopTransmit();
}//GEN-LAST:event_butStopShareActionPerformed

    private void butMsgSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butMsgSendActionPerformed
// TODO add your handling code here:
    if (!jTextField1.getText().equals("")) {
        chater.sendAll("방장 : " + jTextField1.getText());
        jTextField1.setText("");
    }
}//GEN-LAST:event_butMsgSendActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // TODO add your handling code here:
            
        FileDialog dlgOpenFile;
        dlgOpenFile = new FileDialog(parent, "스트리밍 할 파일을 추가합니다.", java.awt.FileDialog.LOAD );
        dlgOpenFile.setVisible(true);
        
        String dir = dlgOpenFile.getDirectory();
        String file = dlgOpenFile.getFile();
        
        if( dir != null || file != null ) {
            comboSource.addItem(file + "|" + dir);
        }
}//GEN-LAST:event_jButton2ActionPerformed

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    // TODO add your handling code here:
    /*
    if (sourceList.getSelectedIndex() > -1) {
        model.removeElementAt(sourceList.getSelectedIndex());
    }*/
}//GEN-LAST:event_jButton3ActionPerformed

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
    // TODO add your handling code here:
    if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER && !jTextField1.getText().equals("")) {          
            chater.sendAll("방장 : " +jTextField1.getText());
            jTextField1.setText("");
    }
}//GEN-LAST:event_jTextField1KeyPressed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton butMsgSend;
    private javax.swing.JButton butStartShare;
    private javax.swing.JButton butStopShare;
    private javax.swing.JComboBox comboSource;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JLayeredPane jLayeredPane2;
    private javax.swing.JLayeredPane jLayeredPane3;
    private javax.swing.JLayeredPane jLayeredPane4;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
    
}
